package com.shipwe.loans.ui.presenter

import android.graphics.Color
import android.view.View
import com.shipwe.loans.MyApps
import com.shipwe.loans.R
import com.shipwe.loans.pro.ShipwePresenter
import com.shipwe.loans.ui.view.IUserPermissionView
import com.shipwe.loans.utils.dialog.TipsDialog
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.permission.OnPermissionCallback
import com.shipwe.permission.Permission
import com.shipwe.permission.XXPermissions
import org.json.JSONArray
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/28 15:41
 * @Annotation：权限页面
 */
class UserPermissionPresenter(private val iView: IUserPermissionView): ShipwePresenter(iView) {

    private var permissionList: ArrayList<JSONObject>? = null
    //当前权限下标
    var curtIndex = 0

    /**
     * 获取权限列表
     */
    fun loadUserPermissionListAction(){
        permissionList = arrayListOf()
        val permissionArray = CustomConfigsHelper.getShipwePermissionsLaunch()
        if (permissionArray != null){
            //手动添加一条
            permissionArray.put(MyApps.app.getString(R.string.permission_app_list_title))
            for (i in 0..<permissionArray.length()){
                val permission = permissionArray.optString(i)
                permissionList!!.add(formatUserPermissionItem(permission))
            }
        }
        iView.showPermissionList(permissionList!!)

        curtIndex = getUserPermissionIndex()
        setUserPermissionStatus()
    }

    /**
     * 下一个
     */
    fun onUserPermissionNextAction(){
        //全部同意
        if (isUserPermissionAgreeAll()){
            iView.showPermissionSuccess()
            return
        }
        //全部完成（拒绝+同意） -> 展示拒绝的权限
        if (curtIndex == permissionList!!.size){
            iView.showPermissionPage(getUserPermissionIndex())
            return
        }
        curtIndex++
        iView.showPermissionPage(curtIndex)
    }

    /**
     * 拒绝权限
     */
    fun onUserPermissionDenyClick(){
        val item = permissionList!![curtIndex]
        item.put("isAgree",false)
        item.put("isClick",true)
        iView.showPermissionBanned()
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_DENY,item.optString("permission"))

        onUserPermissionCheckPageClick(getUserPermissionIndex())
    }

    /**
     * 同意
     */
    fun onUserPermissionAgreeClick(){
        val item = permissionList!![curtIndex]
        val tipsDialog = TipsDialog(iView.getAct(),item.optString("permission"),object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.tipsConfirm -> {
                        hasRequestUserPermissions(item)
                        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_DIALOG_TIPS_OK,item.optString("permission"))
                    }
                    R.id.tipsCancel -> {
                        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_DIALOG_TIPS_CANCEL,item.optString("permission"))
                    }
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.setTitleText(iView.getAct().getString(R.string.dialog_tips))
        tipsDialog.setTipsText(iView.getAct().getString(R.string.permission_agree_tips))

        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_AGREE,item.optString("permission"))
    }

    /**
     * 切换Page
     */
    fun onUserPermissionCheckPageClick(index: Int){
        curtIndex = index
        setUserPermissionStatus()
    }

    /**
     * 已拒绝按钮
     */
    fun onUserPermissionBannedClick(){
        val item = permissionList!![curtIndex]
        XXPermissions.startPermissionActivity(iView.getAct(),item.optString("permission"))
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_BANNED,item.optString("permission"))
    }

    /**
     * onResume
     */
    fun onUserPermissionResume(){
        curtIndex = getUserPermissionIndex()
        setUserPermissionStatus()
    }

    /**
     * 显示权限
     */
    private fun setUserPermissionStatus(){
        //全部允许
        if (isUserPermissionAgreeAll()){
            iView.showPermissionSuccess()
            return
        }
        val item = permissionList!![curtIndex]
        iView.showPermissionPage(curtIndex)

        var isShowAgree = false
        //系统权限
        if (item.optBoolean("isSystem")){
            //是否已获得权限
            val isGranted = XXPermissions.isGranted(iView.getAct(),item.optString("permission"))
            //已获得权限
            if (isGranted){
                isShowAgree = true
            }
        } else {//非系统权限
            if (item.optBoolean("isClick",false) && item.optBoolean("isAgree",false)){
                isShowAgree = true
            }
        }
        if (isShowAgree){
            item.put("isAgree",true)
            item.put("isClick",true)
            iView.showPermissionAuthorized()
            return
        }

        if (item.optBoolean("isClick",false) && !item.optBoolean("isAgree",false)){
            iView.showPermissionBanned()
            return
        }
        iView.showPermissionNotObtained()
    }

    /**
     * 是否全部已授权
     */
    private fun isUserPermissionAgreeAll(): Boolean{
        var isAgreeAll = true
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //已同意跳过
                if (item.optBoolean("isAgree")){
                    continue
                }

                var isAgree = false
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    //是否是系统权限
                    if (item.optBoolean("isSystem")){
                        if (XXPermissions.isGranted(iView.getAct(),item.optString("permission"))){
                            isAgree = true
                        }
                    }
                } else {
                    if (item.optBoolean("isClick")){
                        isAgree = true
                    }
                }

                if (!isAgree){
                    isAgreeAll = false
                    break
                }
            }
        }
        return isAgreeAll
    }

    /**
     * 获取未授权的权限下标
     */
    private fun getUserPermissionIndex(): Int{
        var index = curtIndex
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(iView.getAct(),item.optString("permission"))){
                        index = i
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick",false)){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 获取所有权限列表
     */
    fun getUserPermissionList(): ArrayList<JSONObject>{
        return permissionList!!
    }

    /**
     * 申请权限
     */
    fun hasRequestUserPermissions(item: JSONObject){
        //非系统权限
        if (!item.optBoolean("isSystem")){
            item.put("isAgree",true)
            item.put("isClick",true)
            iView.showPermissionAuthorized()
            //验证是否全部已同意
            if (isUserPermissionAgreeAll()){
                iView.showPermissionSuccess()
                return
            }
            curtIndex = getUserPermissionIndex()
            setUserPermissionStatus()
            return
        }

        val permission = item.optString("permission")
        XXPermissions.with(iView.getAct())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        item.put("isAgree",true)
                        item.put("isClick",true)
                        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_SYSTEM_AGREE,permission)
                        iView.showPermissionAuthorized()
                        //验证是否全部已同意
                        if (isUserPermissionAgreeAll()){
                            iView.showPermissionSuccess()
                            return
                        }
                        curtIndex = getUserPermissionIndex()
                        setUserPermissionStatus()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    item.put("isAgree",false)
                    item.put("isClick",true)
                    //不在询问
                    if (doNotAskAgain){
                        XXPermissions.startPermissionActivity(iView.getAct(),permission)
                        iView.showPermissionBanned()
                        return
                    }
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_SYSTEM_DENY,permission)
                    iView.showPermissionBanned()
                    //验证是否全部已同意
                    if (isUserPermissionAgreeAll()){
                        iView.showPermissionSuccess()
                        return
                    }
                    curtIndex = getUserPermissionIndex()
                    setUserPermissionStatus()
                }
            })
    }

    /**
     * 拼装权限Item
     */
    private fun formatUserPermissionItem(permission: String): JSONObject{
        var item = JSONObject()
        item.put("permission",permission)
        item.put("isAgree",false)
        item.put("isClick",false)
        item.put("isSystem",true)
        when(permission){
            Permission.READ_SMS -> {
                item.put("isMust",false)
                item.put("icon", R.drawable.page_permission_sms_icon)
                item.put("title",getString(R.string.permission_sms_title))
                item.put("titleColor", Color.parseColor("#FF222222"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title","")
                obj1.put("des",getString(R.string.permission_sms_desc))
                msgArray.put(obj1)

                item.put("msgList",msgArray)
            }
            Permission.READ_PHONE_STATE -> {
                item.put("isMust",true)
                item.put("icon",R.drawable.page_permission_phone_state_icon)
                item.put("title",getString(R.string.permission_phone_state_title))
                item.put("titleColor", Color.parseColor("#FF222222"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title","")
                obj1.put("des",getString(R.string.permission_phone_state_desc))
                msgArray.put(obj1)

                item.put("msgList",msgArray)
            }
            MyApps.app.getString(R.string.permission_app_list_title) -> {
                item.put("isSystem",false)
                item.put("isMust",false)
                item.put("icon", R.drawable.page_permission_app_list_icon)
                item.put("title",getString(R.string.permission_app_list_title))
                item.put("titleColor", Color.parseColor("#FF222222"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title","")
                obj1.put("des",getString(R.string.permission_app_list_desc))
                msgArray.put(obj1)

                item.put("msgList",msgArray)
            }
        }
        return item
    }

}